<template>
  <div class="dashboard-container">
    <!-- 门户大屏卡片 -->
    <div class="card">
      <img src="@/assets/portal.png" alt="门户大屏" class="thumbnail" @click="goToScreen('portal')" />
      <div class="button-group">
        <h3>门户大屏</h3>
        <div>
          <el-tooltip class="item" effect="dark" content="参数配置" placement="top">
            <span class="peizhi" @click="openConfigDialog('portal')"></span>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="进入大屏" placement="top">
            <span class="jinru" @click="goToScreen('portal')"></span>
          </el-tooltip>
        </div>
      </div>
    </div>

    <!-- 实时屏幕大屏 -->
    <div class="card">
      <img src="@/assets/realtime.png" alt="实时屏幕大屏" class="thumbnail" @click="goToScreen('realtime')" />
      <div class="button-group">
        <h3>实时屏幕大屏</h3>
        <div>
          <el-tooltip class="item" effect="dark" content="参数配置" placement="top">
            <span class="peizhi" @click="parameterConfiguration()"></span>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="进入大屏" placement="top">
            <span class="jinru" @click="goToScreen('realtime')"></span>
          </el-tooltip>
        </div>
      </div>
    </div>

    <!-- 资产全景大屏 -->
    <div class="card">
      <img src="@/assets/assetPanorama.png" alt="资产全景大屏" class="thumbnail" @click="goToScreen('assetPanorama')" />
      <div class="button-group">
        <h3>资产全景大屏</h3>
        <div>
          <el-tooltip class="item" effect="dark" content="参数配置" placement="top">
            <span class="peizhi" @click="openassetPanorama"></span>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="进入大屏" placement="top">
            <span class="jinru" @click="goToScreen('assetPanorama')"></span>
          </el-tooltip>
        </div>
      </div>
    </div>

    <!-- 大屏门户参数配置弹窗 -->
    <el-dialog title="门户大屏参数配置" :visible.sync="configDialogVisible" :close-on-click-modal="false"
      :close-on-press-escape="false" v-el-drag-dialog width="30%" @close="resetConfigForm">
      <el-form :model="configForm" ref="configForm" label-width="120px">
        <el-form-item label="自动刷新间隔：">
          <el-input v-model.number="configForm.CatInterval" maxlength="3" placeholder="请输入自动刷新间隔"></el-input>
        </el-form-item>
        <el-form-item label="数据统计天数：">
          <el-input v-model.number="configForm.days" maxlength="3" placeholder="请输入数据统计天数"></el-input>
        </el-form-item>
        <el-form-item label='大屏查看密码：' prop="Pwd">
          <el-input v-model="configForm.Pwd" maxlength="30" placeholder="请设置查看密码"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveConfig">确定</el-button>
        <el-button type="info" @click="configDialogVisible = false">取消</el-button>
      </span>
    </el-dialog>
    <!-- 实时屏屏幕参数配置 -->
    <el-dialog :close-on-click-modal="false" :close-on-press-escape=false title="实时屏幕大屏参数配置" top="5vh"
      :visible.sync="dialogVisible" v-el-drag-dialog width="50%">
      <el-form label-width="120px" :model="accountForm" :rules="rules" ref="accountForm">
        <el-row class="ruleMain">
          <el-divider content-position="left">基本规则内容</el-divider>
          <el-form-item label='自动刷新：' prop="Capture">
            <el-checkbox v-model="accountForm.Capture" :true-label="1" :false-label="0">开启</el-checkbox>
            自动播放时间间隔：<el-input v-model.number="accountForm.CatInterval" style="width:200px" @input="restrictNumberInput"
              maxlength="2" placeholder="请输入大于0的数字"></el-input> 秒
          </el-form-item>
          <el-form-item label="屏幕显示：">
            <grid-selector @update-selection="updateGridSelection" :initial-rows="accountForm.Row"
              :initial-cols="accountForm.Column" />
          </el-form-item>
          <device-object-selector :form.sync="accountForm" />
          <el-form-item label='排序模式：' prop="Polling">
            <el-radio v-model="accountForm.Polling" :label="1">按最近采集时间排序</el-radio>
            <el-radio v-model="accountForm.Polling" :label="0">按资产名称排序</el-radio>
          </el-form-item>
          <el-form-item label='超时次数：' prop="Capture">
            <div style="display: flex; align-items: center;">
              <!-- 红色圆圈感叹号图标 -->
              <el-tooltip content="配置为0时不启用，配置为非0时，超过此次数未上送的数据不显示" placement="top">
                <span class="exclamationPoint">
                  !
                </span>
              </el-tooltip>
              <!-- 下拉选择框 -->
              <el-select v-model="accountForm.TimeOut">
                <el-option :value="0" label="不开启"></el-option>
                <el-option :value="3" label="3次"></el-option>
                <el-option :value="5" label="5次"></el-option>
                <el-option :value="10" label="10次"></el-option>
              </el-select>
            </div>
          </el-form-item>
          <el-form-item label='独立获取：' prop="Independence">
            <div style="display: flex; align-items: center;">
              <!-- 红色圆圈感叹号图标 -->
              <el-tooltip content="不勾选表示使用最近录制的屏幕视频，勾选则实时获取屏幕。" placement="top">
                <span class="exclamationPoint">
                  !
                </span>
              </el-tooltip>
              <el-checkbox v-model="accountForm.Independence" :true-label="1" :false-label="0">开启</el-checkbox>
            </div>
          </el-form-item>
          <el-form-item label='大屏查看密码：' prop="Pwd">
            <el-input v-model="accountForm.Pwd" maxlength="30" placeholder="请设置查看密码"></el-input>
          </el-form-item>
        </el-row>
      </el-form>
      <el-divider></el-divider>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit()">确 定</el-button>
        <el-button type="info" @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 资产全景大屏参数配置 -->
    <el-dialog title="资产大屏参数配置" :visible.sync="assetPanoramaDialogVisible" :close-on-click-modal="false"
      :close-on-press-escape="false" v-el-drag-dialog width="30%" @close="assetPanoramaDialogVisible = false">
      <el-form :model="configForm" ref="configForm" label-width="120px">
        <el-form-item label="指定部门" prop="DeviceObjType">
          <el-cascader multiple style="width:100%;" placeholder="请选择部门" ref="cascaderAddr" v-model="asset.DeviceObj"
            clearable :options="deviceObjList" :props="{
              children: 'Children',
              expandTrigger: 'hover',
              label: 'Name',
              value: 'ID',
              emitPath: false,
              multiple: true,
              checkStrictly: true
            }" />
        </el-form-item>
        <el-form-item label='大屏查看密码：' prop="Pwd">
          <el-input v-model="asset.Pwd" maxlength="30" placeholder="请设置查看密码"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="assetSaveConfig">确定</el-button>
        <el-button type="info" @click="assetPanoramaDialogVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import GridSelector from './components/GridSelector.vue'
import DeviceObjectSelector from '@/components/DeviceObjectSelector'
import { connrequest } from '@/api/firstPage'
import { GetDeviceTree, transformToCascaderTree } from "@/utils/index.js";
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
export default {
  components: {
    GridSelector,
    DeviceObjectSelector
  },
  directives: { elDragDialog },
  data() {
    return {
      configDialogVisible: false, // 控制弹窗显示
      dialogVisible: false,
      assetPanoramaDialogVisible: false,
      deviceObjList: [],
      accountForm: {},
      currentScreen: '', // 当前配置的大屏（portal 或 realtime）
      configForm: {
        CatInterval: 10,
        days: 7
      }, // 配置表单数据
      asset: {},
      rules: {
        CatInterval: [
          { validator: this.validateCatInterval, trigger: 'blur' }
        ]
      },
    };
  },
  methods: {
    // 限制输入只能为数字
    restrictNumberInput(value) {
      // 只保留数字，移除非数字字符
      const numValue = value.replace(/[^\d]/g, '')
      // 更新 v-model 值
      this.accountForm.CatInterval = numValue ? Number(numValue) : ''
    },

    // 校验 CatInterval 必须大于0
    validateCatInterval(rule, value, callback) {
      if (!value && value !== 0) {
        callback(new Error('请输入时间间隔'))
      } else if (value <= 0) {
        callback(new Error('时间间隔必须大于0'))
      } else {
        callback()
      }
    },
    stringToMD5(str) {
      return crypto.createHash('md5').update(str).digest('hex');
    },
    // ---------- 门户大屏 ---------------
    // 打开参数配置弹窗
    async openConfigDialog(screen) {
      const data = {
        Filter: {
          FileName: 'param_assetPanorama.json'
        }
      }
      const res = await connrequest('GetUICommonParam', data)
      this.configDialogVisible = true
      this.configForm = { ...this.accountForm, ...res.Data }
    },
    // 保存配置
    async saveConfig() {
      this.$refs.configForm.validate(async (valid) => {
        if (valid) {
          if (!this.configForm.CatInterval || this.configForm.CatInterval < 1) {
            this.$message.info('请输入自动播放时间间隔,最小时间间隔为1秒')
            return
          }
          const data = {
            Filter: {
              FileName: 'param_assetPanorama.json'
            },
            Data: {
              ...this.configForm
            }
          }
          const res = await connrequest('SetUICommonParam', data)
          if (res.Status.StatusCode === 0) {
            this.$message.success('保存成功')
            this.configDialogVisible = false
          }
        }
      });
    },

    // ---------- 实时屏幕大屏 ---------------
    updateGridSelection({ rows, cols }) {
      this.accountForm.Row = rows
      this.accountForm.Column = cols
    },
    async initData(searchobj = {}) {
      try {
        const { DeviceTree } = await GetDeviceTree()
        this.nodeData = DeviceTree
        this.expandArray = [DeviceTree?.[0]?.Name]
      } catch (error) {
        console.error('初始化数据失败:', error)
      }
    },
    async parameterConfiguration() {
      await this.initData()
      const data = {
        Filter: {
          FileName: 'param_real_screen.json'
        }
      }
      const res = await connrequest('GetUICommonParam', data)
      this.dialogVisible = true
      this.accountForm = { ...this.accountForm, ...res.Data }
    },
    async submit() {
      if (!this.accountForm.CatInterval || this.accountForm.CatInterval < 1) {
        this.$message.info('请输入自动播放时间间隔,最小时间间隔为1秒')
        return
      }
      const data = {
        Filter: {
          FileName: 'param_real_screen.json'
        },
        Data: {
          ...this.accountForm
        }
      }
      const res = await connrequest('SetUICommonParam', data)
      if (res.Status.StatusCode === 0) {
        this.$message.success('保存成功')
        this.dialogVisible = false
      }
    },

    // ---------- 资产全景大屏 ---------------
    async GetDepartmentDeviceSumTree() {
      const res = await connrequest('GetDepartmentDeviceSumTree')
      const deviceObjList = transformToCascaderTree(res.Data.Department)
      this.deviceObjList = deviceObjList
    },
    async openassetPanorama() {
      const data = {
        Filter: {
          FileName: 'param_asset_panoramic.json'
        }
      }
      const res = await connrequest('GetUICommonParam', data)
      this.GetDepartmentDeviceSumTree()
      this.assetPanoramaDialogVisible = true
      this.asset = { ...this.asset, ...res.Data }
    },
    async assetSaveConfig() {
      const data = {
        Filter: {
          FileName: 'param_asset_panoramic.json'
        },
        Data: {
          ...this.asset
        }
      }
      const res = await connrequest('SetUICommonParam', data)
      if (res.Status.StatusCode === 0) {
        this.$message.success('保存成功')
        this.assetPanoramaDialogVisible = false
      }
    },
    // 重置表单
    resetConfigForm() {
      this.configForm = {}
    },
    // 提取 URL 的基础部分，截取到包含 `#/` 的位置。
    extractBaseUrl(fullUrl) {
      const index = fullUrl.indexOf('#/');
      if (index !== -1) {
        return fullUrl.substring(0, index + 2); // 截取到 #/
      }
      return fullUrl; // 如果没有 #/，返回完整 URL
    },
    // 跳转到大屏页面
    goToScreen(screen) {
      let baseUrl = this.extractBaseUrl(window.location.href);
      if (screen === 'portal') {
        baseUrl = `${baseUrl}bigScreen`;
      } else if (screen === 'realtime') {
        baseUrl = `${baseUrl}realTimeScreen`;
      } else if (screen === 'assetPanorama') {
        // this.$message.info('开发中')
        // return
        baseUrl = `${baseUrl}assetPanorama`;
      }
      window.open(baseUrl, '_blank');
    }
  }
};
</script>

<style lang="scss" scoped>
.dashboard-container {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
  gap: 10px;
  padding: 10px;
}

.card {
  width: 400px;
  /* 固定宽度 */
  height: 290px;
  /* 固定高度，可根据需要调整 */
  padding: 10px;
  border: 1px solid #e6e6e6;
  border-radius: 8px;
  text-align: center;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  box-sizing: border-box;
  /* 确保padding不影响宽高 */
  flex-shrink: 0;
  /* 防止在flex容器中缩放 */
  overflow: hidden;

  /* 防止内容溢出导致变形 */
  .jinru,
  .peizhi {
    display: inline-block;
    width: 32px;
    height: 32px;
    margin-right: 10px;
    cursor: pointer;
  }

  .jinru {
    background: url('~@/assets/jinru@2x.png') center center no-repeat;
    background-size: contain;
  }

  .peizhi {
    background: url('~@/assets/peizhi@2x.png') center center no-repeat;
    background-size: contain;
  }

  .jinru:hover {
    background: url('~@/assets/jinru1@2x.png') center center no-repeat;
    background-size: contain;
  }

  .peizhi:hover {
    background: url('~@/assets/peizhi1@2x.png') center center no-repeat;
    background-size: contain;
  }

}

.thumbnail {
  width: 100%;
  height: 210px;
  object-fit: fill;
  border-radius: 4px;
  margin-bottom: 10px;
  flex-grow: 1;
  cursor: pointer;
}

h3 {
  margin: 10px 0;
  font-size: 18px;
  color: #333;
}

.button-group {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
}

.exclamationPoint {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 16px;
  height: 16px;
  background-color: #ff4d4f;
  border-radius: 50%;
  color: white;
  font-size: 12px;
  margin-right: 8px;
  cursor: pointer;
}
</style>